package com.inspector.app.ui.chat.socket;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Socket服务类
 */
public class SocketService {
    private static final String TAG = "SocketService";
    private static final int INITIAL_DELAY = 1000; // 初始延迟时间，1秒
    private static final int MAX_DELAY = 32000; // 最大延迟时间，32秒
    private static final int MAX_RECONNECT_ATTEMPTS = 5; // 最大重连尝试次数

    private WebSocketClient mWebSocketClient;
    private boolean isConnected = false;
    private boolean isClosed = false; // 标志是否已经关闭
    private SocketServiceListener mListener;
    private int mReconnectAttempts = 0;

    private final Handler mHandler = new Handler(Looper.getMainLooper()); //用于切换回UI线程

    public SocketService(final String serverUrl, SocketServiceListener listener) {
        this.mListener = listener;
        try {
            mWebSocketClient = new WebSocketClient(new URI(serverUrl)) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    if (isClosed) return; // 如果已经关闭，直接返回
                    isConnected = true;
                    mReconnectAttempts = 0; // 重置重连尝试次数
                    Log.i(TAG, "已连接到服务器");
                    mHandler.post(() -> {
                        if (mListener != null) {
                            mListener.onConnected();
                        }
                    });
                }

                @Override
                public void onMessage(String message) {
                    if (isClosed) return; // 如果已经关闭，直接返回
                    Log.i(TAG, "收到消息: " + message);
                    mHandler.post(() -> {
                        if (mListener != null) {
                            mListener.onMessageReceived(message);
                        }
                    });
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    if (isClosed) return; // 如果已经关闭，直接返回
                    isConnected = false;
                    Log.i(TAG, "已从服务器断开连接");
                    mHandler.post(() -> {
                        if (mListener != null) {
                            mListener.onDisconnected();
                        }
                    });
                    scheduleReconnect();
                }

                @Override
                public void onError(Exception ex) {
                    if (isClosed) return; // 如果已经关闭，直接返回
                    isConnected = false;
                    Log.e(TAG, "WebSocket错误: " + ex.getMessage());
                    mHandler.post(() -> {
                        if (mListener != null) {
                            mListener.onError();
                        }
                    });
                }
            };
            mWebSocketClient.connect();
        } catch (URISyntaxException e) {
            Log.e(TAG, "建立连接失败", e);
        }
    }

    public void scheduleReconnect() {
        if (!isConnected && !isClosed && mReconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
            int delay = Math.min(INITIAL_DELAY * (1 << mReconnectAttempts), MAX_DELAY);
            delay += new Random().nextInt(INITIAL_DELAY);
            mHandler.postDelayed(this::doReconnect, delay);
            mReconnectAttempts++;
        } else {
            Log.e(TAG, "达到最大重连次数，停止重连");
            if (mListener != null) {
                mHandler.post(() -> mListener.onError());
            }
        }
    }

    private void doReconnect() {
        if (!isConnected && !isClosed && mWebSocketClient != null) {
            try {
                mWebSocketClient.reconnect();
            } catch (Exception e) {
                Log.e(TAG, "重连失败", e);
            }
        }
    }

    public void sendMessage(String content) {
        if (isConnected && !isClosed) {
            mWebSocketClient.send(content);
        } else {
            Log.e(TAG, "WebSocket未连接");
        }
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void close() {
        isClosed = true; // 标记为已关闭
        if (mWebSocketClient != null) {
            mWebSocketClient.close();
            mWebSocketClient = null;
        }
        isConnected = false;
        mHandler.removeCallbacksAndMessages(null); // 清除所有延迟任务
    }
}
